package com.yy.launchercaijing

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import com.just.agentweb.AgentWeb

class WebAppActivity : AppCompatActivity() {
    private var agentWeb: AgentWeb? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_app)
        enableFullScreen()

        var url = intent.getStringExtra("url")
        // 初始化 AgentWeb 并加载网页
        agentWeb = AgentWeb.with(this)
            .setAgentWebParent(findViewById(R.id.webContainer), ViewGroup.LayoutParams(-1, -1))
            .useDefaultIndicator() // 使用默认进度条
            .createAgentWeb()
            .ready()
            .go(url) // 要加载的网址


        findViewById<ImageView>(R.id.imgv_back).setOnClickListener {
            onBackPressed()
        }
    }

    // 重写返回键事件，让 AgentWeb 支持网页后退
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (agentWeb != null && agentWeb!!.handleKeyEvent(keyCode, event)) {
            true
        } else {
            super.onKeyDown(keyCode, event)
        }
    }

    override fun onDestroy() {
        agentWeb?.webLifeCycle?.onDestroy()
        super.onDestroy()
    }

    override fun onResume() {
        agentWeb?.webLifeCycle?.onResume()
        super.onResume()
        enableFullScreen()
    }

    override fun onPause() {
        agentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    private fun enableFullScreen() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11 及以上版本
            window.insetsController?.let { controller ->
                controller.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
                controller.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            }
        } else {
            // Android 11 以下版本
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    )
        }
    }
}